package com.edu.stress.test.controller;


import com.edu.stress.test.service.RegisterService;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.log4j.Logger;

public class RegisterController extends AbstractJavaSamplerClient {

    private static final Logger logger = Logger.getLogger(RegisterController.class);


    /**
     * 主要用于设置传入的参数
     * @return
     */
    public Arguments getDefaultParameters() {
        Arguments params = new Arguments();
        params.addArgument("vin", "");
        return params;
    }

    /**
     * 为性能测试时的线程运行体
     * @param context
     * @return
     */
    public SampleResult runTest(JavaSamplerContext context) {
        String vin = context.getParameter("vin");

        SampleResult sr = new SampleResult();
        sr.setSampleLabel("注册接口");
        sr.sampleStart();

        try {
            RegisterService register = new RegisterService(vin);

            boolean res = register.register();

            if (res) {
                sr.setResponseData("deviceId||secret:" + register.getDeviceId()+"||"+register.getSecret(), null);// 将数据打印到查看结果树当中
                sr.setDataType(SampleResult.TEXT);

                sr.setResponseMessage(vin);
                sr.setResponseCodeOK();
                sr.setSuccessful(true);
            } else {
                logger.info("vin:"+vin+"注册失败");
            }

        } catch (Exception e) {
            sr.setSuccessful(false);
            e.printStackTrace();
        } finally {
            sr.sampleEnd();
        }
        return sr;
    }

    public static void main(String[] args) {
        Arguments params = new Arguments();
        params.addArgument("vin", "performance777777");
        JavaSamplerContext context = new JavaSamplerContext(params);
        RegisterController test = new RegisterController();
        test.setupTest(context);
        test.runTest(context);
        test.teardownTest(context);
    }
}
